package com.qdsgjsfk.vision.socket;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.eventbus.Err;
import com.qdsgjsfk.vision.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;


import jz.joyoung.robot.util.LogUtil;

/**
 * Created by HP on 2018/11/16.
 */

public class SocketServer1 {
    //    private ServerSocket server;
    private DatagramSocket socket;
    private DatagramPacket packet;
    private InputStream in;
    private String str = null;
    private boolean isClint = false;
    public static Handler ServerHandler;
    private byte[] data = new byte[1024];
    private InetSocketAddress address;
    int port;
    private SocketAddress toAddress;
    private long keepAliveDelay = 10000;
    private long lastSendTime;
    private InetAddress inetAddress;
    private Context mContext;


    /**
     * @effect 初始化服务端
     */
//    public SocketServer(int port) {
////        try {
////
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//
//    }

    private String tempData = "";
    private String tempDataOne = "";

    /**
     * @effect socket监听数据
     */
    public void beginListen() {

        try {
            String site = getLocalIpAddress();
            if (TextUtils.isEmpty(site))
                return;
            String[] ipStr = site.split("\\.");
            byte[] ipBuf = new byte[4];
            for (int i = 0; i < 4; i++) {
                ipBuf[i] = (byte) (Integer.parseInt(ipStr[i]) & 0xff);
            }
            inetAddress = InetAddress.getByAddress(ipBuf);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


        new Thread(() -> {
            try {
                address = new InetSocketAddress(inetAddress, 7778);
                Log.e("address===", address.toString());
                socket = new DatagramSocket(address);
//                    socket = new DatagramSocket( 7778 );
                isClint = true;
                data = new byte[2048];
                packet = new DatagramPacket(data, data.length);
                while (true) {
                    socket.receive(packet);
//                        InetAddress addr = packet.getAddress();
//                        int port = packet.getPort();
//                        data = packet.getData();
                    toAddress = packet.getSocketAddress();
//                        System.out.println("Message Content: " + new String(data));
//                        System.out.println("Receive From " + addr + ":" + port);
//                        EventBus.getDefault().postSticky(new Err(new String(data)));
//                        System.out.println(new String(data));
                    tempData = tempData + " " + new String(packet.getData()).substring(0, packet.getLength());
                    tempDataOne = new String(packet.getData(), packet.getOffset(), packet.getLength());

                    Log.e("接收的数据tempData1===", tempDataOne);
//                        Looper.prepare();
//                        Toast.makeText( context, tempData1, Toast.LENGTH_SHORT ).show();
//                        Looper.loop();
                    if (getJSONType(tempDataOne)) {
                        try {
                            JSONObject object = new JSONObject(tempDataOne);
                            int code = object.getInt("code");
                            String value = object.getString("value");
                            if (code == 100) { //代表连接设备成功
                                Looper.prepare();
                                ToastUtil.showToastCenter(mContext, value);
                                Looper.loop();
//                                EventBus.getDefault().postSticky(new BlueTooth(value, 100));
                                tempDataOne = "";
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        try {
                            JSONObject object = new JSONObject(tempDataOne);
                            EventBus.getDefault().postSticky(new BlueTooth(tempDataOne, 110));
                            tempDataOne = "";
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (tempData.trim().endsWith("E")) {
                            EventBus.getDefault().postSticky(new BlueTooth(tempData, 1));
                            tempData = "";
                        } else if (tempData.trim().endsWith("End")) {
                            EventBus.getDefault().postSticky(new BlueTooth(tempData, 2));
                            tempData = "";
                        } else {
                            EventBus.getDefault().postSticky(new BlueTooth(tempData.trim(), 3));
                            tempData = "";
                        }
                    }

                }

            } catch (IOException e) {
                e.printStackTrace();
                if (socket != null) {
                    socket.isClosed();
                }
            }
        }).start();
    }

    private int getWifiApState(Context mContext) {
        WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        try {
            assert wifiManager != null;
            Method method = wifiManager.getClass().getMethod("getWifiApState");
            return (int) (Integer) method.invoke(wifiManager);
        } catch (Exception e) {
            return -1;
        }
    }

    public SocketServer1(Context context) {
        this.mContext = context;
    }

    private String getLocalIpAddress() {
        if (getWifiApState(mContext) == 13) {
            return "192.168.43.1";
        } else {
            try {
                String ipv4;
                ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface ni : nilist) {
                    ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                    for (InetAddress address : ialist) {
                        if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                            ipv4 = address.getHostAddress();
                            return ipv4;
                        }
                    }
                }

            } catch (SocketException ex) {
                Log.e("localip", ex.toString());
            }

        }
//        }
        return null;
    }

    /**
     * @effect socket服务端发送信息
     */
    public void sendMessage(final String chat) {
        Thread thread = new Thread(() -> {
            try {
                if (!socket.isClosed()) {
                    data = chat.getBytes();
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    packet.setSocketAddress(toAddress);
                    socket.send(packet);
                    System.out.println("==message sended     " + new String(data));
                } else {
                    EventBus.getDefault().postSticky(new Err("视力表未连接"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                EventBus.getDefault().postSticky(new Err("视力表未连接"));
            }
        });
        thread.start();
    }

    public void close() {
        if (socket == null) {
            return;
        }
        socket.close();
    }


    public void getSocketClose() {
        if (getSocket == null) {
            return;
        }
        getSocket.close();
    }


    private InetAddress address2;
    private DatagramSocket getSocket;
    private byte[] buf = new byte[50];
    private DatagramPacket datapacket;

    /**
     * @effect 开启线程建立连接开启电子视力表
     */
    public void openClientThread(String msg, String site, int port) {
        //                    datagramPacket = new DatagramPacket("a".getBytes(),"a".getBytes().length,address,port);
        //                    socket = new DatagramSocket();
        //                    forIn();
        //                    sendMsg();
        //                    while (true) {
        //                        System.out.println("==block for receive messages...");
        //                        getSocket.receive(datapacket);
        //                        buf = datapacket.getData();
        //                        str = new String(buf);
        //                        if (str != null) {
        //                            Message msg = new Message();
        //                            msg.obj = str;
        //                            mHandler.sendMessage(msg);
        //                        }
        //                        System.out.println("Message Content: " + str);
        //                    }
        Thread thread = new Thread(() -> {

            try {
                String[] ipStr = site.split("\\.");
                byte[] ipBuf = new byte[4];
                for (int i = 0; i < 4; i++) {
                    ipBuf[i] = (byte) (Integer.parseInt(ipStr[i]) & 0xff);
                }
                address2 = InetAddress.getByAddress(ipBuf);
//                    datagramPacket = new DatagramPacket("a".getBytes(),"a".getBytes().length,address,port);
//                    socket = new DatagramSocket();
//                    forIn();
                getSocket = new DatagramSocket();
                InetSocketAddress toAddress = new InetSocketAddress(address2, port);
                LogUtil.e("IPAddress---" + address2 + "----------" + toAddress);
                buf = msg.getBytes();
                datapacket = new DatagramPacket(buf, buf.length);
                datapacket.setSocketAddress(toAddress);
                getSocket.send(datapacket);
//                    sendMsg();
//                    while (true) {
//                        System.out.println("==block for receive messages...");
//                        getSocket.receive(datapacket);
//                        buf = datapacket.getData();
//                        str = new String(buf);
//                        if (str != null) {
//                            Message msg = new Message();
//                            msg.obj = str;
//                            mHandler.sendMessage(msg);
//                        }
//                        System.out.println("Message Content: " + str);
//                    }
            } catch (UnknownHostException e) {
                e.printStackTrace();
                Log.i("socket", "6");
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("socket", "7");
            }

        });
        thread.start();
    }


    /**
     * //     * @steps write();
     * //     * @effect 发送消息
     * //     *
     */
    public void sendMsg() {
        new Thread(() -> {
            while (true) {
                if (System.currentTimeMillis() - lastSendTime > keepAliveDelay) {
                    try {
                        DatagramPacket datapacket;
                        InetSocketAddress toAddress = new InetSocketAddress(address2, 6669);

                        byte[] buf = new byte[50];
                        datapacket = new DatagramPacket(buf, buf.length);
                        datapacket.setSocketAddress(toAddress);
                        getSocket.send(datapacket);
                        System.out.println("==message sended");
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("重连");
                    }
                    lastSendTime = System.currentTimeMillis();
                } else {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("bbbbbbbbbbbbbb");
                    }
                }
            }
        }).start();

    }

    private boolean getJSONType(String str) {

        str = str.trim();

        if (str.startsWith("{") && str.endsWith("}")) {

            return true;

        } else return str.startsWith("[") && str.endsWith("]");

    }
}